<?php
$table_name = "verse";

header( 'Content-Type: text/html; charset=utf-8' );
//session_cache_limiter('private');

require_once ("../conf/conf.php");
require_once ("../locales/ro.php");
require ("../include/constants.php");
require ("../include/function.php");

$action = isset ($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : "get_by_id");

session_start();

if($action == 'get_by_id'){
    $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);
    echo getVerseById();
    db_disconnect($connection);
} else if($action == 'get_details'){
    $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);
    echo getDetails();
} else {
    echo renderExpectationFailed();
}

// ====================================================
function getDetails(){
    $id = (int)$_GET['id'];
    $jsonObj = array('id'=>$id);
    if($id){
        $sql = "SELECT chapter.book_id as book, chapter.number as chapter, verse.number as verse ".
            "FROM verse JOIN chapter ON (verse.chapter_id = chapter.id) ".
            "WHERE verse.id = $id";
        $jsonObj = sql2JSONObject($sql);
    }
	return json_encode($jsonObj[0]);
}

// ====================================================
function getVerseById(){
//    $book = $_POST['book'];
//	$chapter = $_POST['chapter'];
	$id = (int)$_GET['id'];
	$book = (int)$_GET['b'];
	$chapter = (int)$_GET['c'];
	$verse = (int)$_GET['v'];

	$sql = "SELECT book.name, chapter.number, verse.number, verse.text ".
                "FROM verse JOIN chapter ON (verse.chapter_id = chapter.id) ".
                "JOIN book ON (chapter.book_id = book.id) WHERE ";
    if($id || ($book && $chapter && $verse)){
        if($id){
			$sql .= "verse.id = $id";
		} else {
			$sql .= "book.id = $book AND chapter.number = $chapter AND verse.number = $verse";
		}
		
        $result = do_query($sql);
        $verseResult = mysql_fetch_array($result);
		if($verseResult){
			return "<b>".$verseResult[0]." ".$verseResult[1].":".$verseResult[2]."</b><br/>".$verseResult[3];
		} else {
			return '<i>verset inexistent</i>';
		}
    } else {
        return "Please specify url like : verse.php?id=1";
    }
}
?>